<script>

function hasClass(elem, cls) {
  cls = cls || '';
  if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时，返回false
  return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
}

function addClass(elem, cls) {
  if (!hasClass(elem, cls)) {
    elem.className = elem.className === '' ? cls : elem.className + ' ' + cls;
  }
}

function removeClass(elem, cls) {
  if (hasClass(elem, cls)) {
    var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' ';
    while (newClass.indexOf(' ' + cls + ' ') >= 0) {
      newClass = newClass.replace(' ' + cls + ' ', ' ');
    }
    elem.className = newClass.replace(/^\s+|\s+$/g, '');
  }
}

export default {
  functional: true,

  props: {
    scope: {
      type: Object,
      required: true,
    },
    fieldName: {
      type: String,
      required: true,
    },
    row: {
      type: Object,
      required: true,
    },
    render: {
      type: Function,
      required: true,
    },
  },

  render(h, ctx) {
    const params = {
      row: ctx.props.row,
      index: ctx.props.scope.$index,
      rowNum: ctx.props.scope.$index,
      fieldName: ctx.props.fieldName,
    };
    let label = ctx.props.row[ctx.props.fieldName];
    const cellOption = {
      class: `column-cell ${label === '1' ? 'is-disabled' : ''}`,
      on: {
        click: (e) => {
          let target = e.target;
          if (hasClass(target, 'is-disabled')) {
            console.log('disabled');
            return;
          }

          console.log('click => ', ctx, target);
          const cells = ctx.parent.$el.querySelectorAll('.column-cell');
          if (cells.length > 0) {
            Array.from(cells).forEach(elem => {
              if (hasClass(elem, 'is-active')) {
                removeClass(elem, 'is-active');
              } else {

              }
            });
          } else {
            addClass(target, 'is-active');
          }

          setTimeout(() => {
            if (isChecked) {
              addClass(target, 'is-active');
            } else {
              removeClass(target, 'is-active');
            }
          }, 200);


          // ctx.$emit('select', { el: target, label, params });
        },
      },
    };

    return h('div', cellOption, label);
  },
};

</script>
